package org.eclipse.swt.snippets;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;

public class ToolMenuItem {

    private ToolItem toolItem;
    private MenuItem menuItem;

    public ToolMenuItem(Menu menu, ToolBar toolBar, int style) {
        toolItem = new ToolItem(toolBar, style);
        menuItem = new MenuItem(menu, style);
    }

    public void setText(String string) {
        toolItem.setText(string);
        menuItem.setText(string);
    }

    public void setAccelerator(int accelerator) {
        menuItem.setAccelerator(accelerator);
        String[] t = new String[4];
        if ((accelerator & SWT.CONTROL) != 0) {
            t[0] = "Ctrl";
        }
        if ((accelerator & SWT.ALT) != 0) {
            t[1] = "Alt";
        }
        if ((accelerator & SWT.SHIFT) != 0) {
            t[2] = "Shift";
        }
        int key = accelerator & SWT.KEY_MASK;
        Character c = new Character((char) key);
        t[3] = c.toString();
        if (key == SWT.F5) {
            t[3] = "F5";
        }

        StringBuilder b = new StringBuilder(menuItem.getText()).append("\t");
        for (String s : t) {
            if (s != null) {
                b.append(s).append("+");
            }
        }
        b.setLength(b.length() - 1);
        menuItem.setText(b.toString());
    }

    public void setImage(Image image) {
        toolItem.setImage(image);
        menuItem.setImage(image);
    }

    public void addSelectionListener(SelectionListener listener) {
        toolItem.addSelectionListener(listener);
        menuItem.addSelectionListener(listener);
    }
}
